Заменить все изображения на странице их свойствами src - PullRequest
0 голосов
/ 22 сентября 2018

Мне нужно создать букмарклет, заменив все изображения на месте строками, которые будут URL-адресами этих изображений.Я не JS парень, поэтому я могу показать свой недействительный код, чтобы получить представление о том, что я хочу.

это примерно так:

var tags = document.getElementsByTagName("img");
for (var i = 0; i < tags.length; i++) { 
var image = tags[i].getAttribute("src");
tags[i].innerHTML = image; }

Я знаю, что это должно быть оченьэто легко сделать, но я не смог найти никакого рабочего решения.

Ответы [ 3 ]

0 голосов
/ 22 сентября 2018

Вы, вероятно, можете установить display:none для всех изображений и создать текстовый узел с атрибутом src:

var tags = document.getElementsByTagName("img");
for (var i = 0; i < tags.length; i++) { 
var image = tags[i].getAttribute("src");
  tags[i].style.display = 'none';
  var el = document.createTextNode(image);
  document.getElementById('container').appendChild(el);
}
<div id="container">
  <img src="/image1"/>
  <img src="/image2"/>
  <img src="/image3"/>
  <img src="/image4"/>
</div>
0 голосов
/ 22 сентября 2018

вы можете попробовать это.это прекрасно работает и использует pure js (без какой-либо библиотеки):

document.querySelectorAll("img").forEach((i)=>{
  i.insertAdjacentElement("afterend", ((sc)=>{sc.classList.add("replaced-text");  sc.innerHTML=i.src; return sc;})(document.createElement("span")));
  i.parentNode.removeChild(i);
});
.replaced-text{
  display: block;
  color: #300;
}
<div>
  <img src="https://lorempixel.com/50/50/nature/1" alt=""/>
  <img src="https://lorempixel.com/50/50/nature/2" alt=""/>
  <img src="https://lorempixel.com/50/50/nature/3" alt=""/>
  <img src="https://lorempixel.com/50/50/nature/4" alt=""/>
  <img src="https://lorempixel.com/50/50/nature/5" alt=""/>
  <img src="https://lorempixel.com/50/50/nature/6" alt=""/>
</div>
0 голосов
/ 22 сентября 2018

Я бы предложил:

// retrieve all <img> elements in the document,
// using document.querySelector(); then iterate
// over that NodeList using
// NodeList.prototype.forEach():
document.querySelectorAll('img').forEach(

  // 'el' is a reference to the current element of
  // of the NodeList of elements; and here we use
  // Node.replaceWith() to replace the current ('el')
  // Node with a textNode, with the node-value set to
  // the src of the element:
  (el) => el.replaceWith(document.createTextNode(el.src))
);

// retrieve all <img> elements in the document,
// using document.querySelector(); then iterate
// over that NodeList using
// NodeList.prototype.forEach():
document.querySelectorAll('img').forEach(

  // 'el' is a reference to the current element of
  // of the NodeList of elements; and here we use
  // Node.replaceWith() to replace the current ('el')
  // Node with a textNode, with the node-value set to
  // the src of the element:
  (el) => el.replaceWith(document.createTextNode(el.src))
);
<ul>
  <li><img src="https://i.stack.imgur.com/wa24z.jpg"></li>
  <li><img src="https://i.stack.imgur.com/jS9JB.jpg"></li>
  <li><img src="https://i.stack.imgur.com/ifMfn.jpg"></li>
  <li><img src="https://i.stack.imgur.com/rlEus.jpg"></li>
  <li><img src="https://i.stack.imgur.com/sRoGY.jpg"></li>
  <li><img src="https://i.stack.imgur.com/0dsoZ.jpg"></li>
  <li><img src="https://i.stack.imgur.com/GO9Tx.jpg"></li>
</ul>

Демонстрация JS Fiddle .

Выше, с использованием функций ES6 (let, childNode.replaceWith() и функции со стрелками) не будут работать в браузерах, которые не поддерживают ES6;Ниже приведен альтернативный вариант использования ES5, который может быть более надежным:

function naiveReplaceWith(originalNode, replacementNode) {

  // here we navigate from the originalNode (the node to be replaced)
  originalNode
    // to its parentNode:
    .parentNode
    // and call parentNode.replaceChild:
    .replaceChild(
      // supplying the replacement-node as the first argument:
      replacementNode,
      // and the original node as the second:
      originalNode);
}

// here we use Array.prototype.slice(), along with Function.prototype.call,
// to allow us to apply the Array.prototype.forEach() to the Array-like
// NodeList returned by document.querySelectorAll():
Array.prototype.slice.call(document.querySelectorAll('img')).forEach(function(el) {
  // using the anonoymous function on each of the elements in the Array of elements:
  naiveReplaceWith(el, document.createTextNode(el.src));
});
<ul>
  <li><img src="https://i.stack.imgur.com/wa24z.jpg"></li>
  <li><img src="https://i.stack.imgur.com/jS9JB.jpg"></li>
  <li><img src="https://i.stack.imgur.com/ifMfn.jpg"></li>
  <li><img src="https://i.stack.imgur.com/rlEus.jpg"></li>
  <li><img src="https://i.stack.imgur.com/sRoGY.jpg"></li>
  <li><img src="https://i.stack.imgur.com/0dsoZ.jpg"></li>
  <li><img src="https://i.stack.imgur.com/GO9Tx.jpg"></li>
</ul>

Демонстрация JS Fiddle .

Если вы хотите, чтобы текст src был активной ссылкой,чтобы пользователь мог перейти по ссылке на исходное изображение:

// a named function that takes a couple of arguments,
// the URL to be the href of the created element, and
// the String which will be the text-content of the
// created elemeent:
let anchorCreate = (href, text) => {

  // creating an <a> element:
  let a = document.createElement('a');

  // setting the href property:
  a.href = href;

  // setting the textContent property; if there is
  // no supplied text then the textContent will be
  // set to the href:
  a.textContent = text || href;

  return a;
}
// retrieve all <img> elements in the document,
// using document.querySelector(); then iterate
// over that NodeList using
// NodeList.prototype.forEach():
document.querySelectorAll('img').forEach(

  // here we replace the current element ('el') with
  // the content returned from the function:
  (el) => el.replaceWith(anchorCreate(el.src))

);
<ul>
  <li><img src="https://i.stack.imgur.com/wa24z.jpg"></li>
  <li><img src="https://i.stack.imgur.com/jS9JB.jpg"></li>
  <li><img src="https://i.stack.imgur.com/ifMfn.jpg"></li>
  <li><img src="https://i.stack.imgur.com/rlEus.jpg"></li>
  <li><img src="https://i.stack.imgur.com/sRoGY.jpg"></li>
  <li><img src="https://i.stack.imgur.com/0dsoZ.jpg"></li>
  <li><img src="https://i.stack.imgur.com/GO9Tx.jpg"></li>
</ul>

JS Fiddle demo .

Ссылки:

...