将元素值更改为其他符号

时间:2019-03-24 04:55:56

标签: javascript

大家好,

我正在尝试通过使用不带任何框架的纯js更改体内每个元素的值。

例如,您打开控制台插入js,它将主体中每个元素的所有值更改为其他符号。

因此,基本上我可以为用户获得网站上所有可见的单词,而无需任何html降价。

like:

<li>This is text</li> 

t->p
h->s
i->e
s->l
e->o
x->z

将是

<li>Psel el pozp</li>

所以,不知道如何遍历每个元素的值。 这就是我尝试过的

var elems = document.body.getElementsByTagName("*");

for (i = 0; i < elems.length; i += 1) {
   if (elems[i].innerHTML.indexOf('<script') != -1){
       console.log(elems[i]);
   } else {
       continue;
   }
}

function validate(element){
    if(element.indexOf('<div') == -1){
        return false;
    } else if(element.indexOf('<script') == -1){
        return false;
    } else {
        return true;
    }
}

但无法正常工作。

已更新: 我认为这是我的坏事。我没有说我需要即时更改值。我的意思是,如果我在控制台中插入代码,它应该遍历每个元素,获取其值,通过将每个字母替换为另一个字母来更改值,然后将值放回原来的位置。最终,它在网络上看起来有所不同。预先谢谢你。

所以我需要代码遍历每个元素,获取其值,对其进行处理,然后将其放回原位。 粗体是我不能做的。谢谢大家。

3 个答案:

答案 0 :(得分:0)

首先,在您的for循环中,将呼叫添加到validate。然后在validate中,添加文本替换:

var elems = document.body.getElementsByTagName("*");

for (i = 0; i < elems.length; i += 1) {
   if (elems[i].innerHTML.indexOf('<script') != -1){
       console.log(elems[i]);
   } else {
       validate(elems[i]);
   }
}

function validate(element){
    if(element.indexOf('<div') == -1){
        return false;
    } else if(element.indexOf('<script') == -1){
        return false;
    } else {
        element.innerText = element.innerText.replace("t", "p"); //Add the others as well
    }
}

答案 1 :(得分:0)

.textContent.innerText

  

“因此,基本上,我可以为用户获得网站上所有可见的单词,而无需任何HTML标记。”
   大写和语法更正是我的

只需使用.textContent.innerText属性就可以轻松地从HTML中提取文本。结果与标准之间的微小不一致之间存在一些显着差异,请参见上面的链接和下面的演示。


演示

运行演示并单击Results链接或滚动到最底部

var content = document.getElementById('content');

var tC = document.getElementById('textContent');
tC.textContent = content.textContent;

var iT = document.getElementById('innerText');
iT.innerText = content.innerText;
<!DOCTYPE html>
<html>

<head>
  <link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.2.1/css/bootstrap.min.css" rel="stylesheet">
  <style>
    html {
      scroll-behavior: smooth
    }
  </style>
</head>

<body>
  <div id='content' class='container'>
    <header id='top' class='container'>
      <hgroup class='row'>
        <h1>Home</h1>
      </hgroup>
      <nav class='row'>
        <ul class='nav col-12'>
          <li class='p-2'><a href='#a0'>Section 1</a></li>
          <li class='p-2'><a href='#a1'>Section 2</a></li>
          <li class='p-2'><a href='#a2'>Section 3</a></li>
          <li class='p-2'><a href='#a3'>Article</a></li>
          <li class='p-2'><a href='#a4'>Results</a></li>
        </ul>
      </nav>
    </header>
    <hr>
    <main class='container'>
      <section id='a0' class='row'>
        <article class='col-12'>
          <h2>Section I</h2>
          <p>Lorem ipsum dolor sit amet, eos nonumy omittam ex. No dicant tibique accusamus pri, sed omnis posidonium ad. In sea dico honestatis, ex repudiare reprimique delicatissimi mea. Sit dicta moderatius ad, natum convenire usu ei. Est no graece laboramus
            deterruisset. </p>
        </article>
      </section>
      <section id='a1' class='row'>
        <article class='col-12'>
          <h2>Section II</h2>
          <p>Mundi nemore iisque in nec. An dolorum intellegat conclusionemque eos, ad labore omittam mel. Te nam wisi omittam patrioque, oporteat honestatis intellegebat cu mei. Odio cibo omittantur te sed.</p>
        </article>
      </section>
      <section id='a2' class='row'>
        <article class='col-12'>
          <h2>Section III</h2>
          <p>Alii commodo ne sea, eu pro legimus signiferumque. At mei nisl facete adolescens, et mel eleifend voluptatibus. Qui ei wisi sonet noster, est solum posidonium scribentur et, sea nobis verear ut. Nemore admodum usu ne.</p>
        </article>
      </section>
      <hr>
      <section id='a3' class='row'>
        <article class='col-12'>
          <h2>Article</h2>
          <p>Lorem ipsum dolor sit amet, quot erroribus voluptatum in pri. Fabulas vocibus insolens his ex. Vide laboramus ius et, at sit adhuc doctus luptatum, et sit dicat inani democritum. His liber blandit pericula id, an fugit reformidans neglegentur
            cum. Indoctum intellegat et pro, sed fabulas ocurreret eu. Nam ut fabulas inciderint, iracundia conceptam ne vix, quo offendit inimicus torquatos in.</p>
          <div class='row'>
            <aside class='col-4 float-left'>
              <blockquote>
                <p>Duo illum assum discere ne, sed cu posse alterum accusam. Cum an error pertinacia, aperiam deleniti</p>
              </blockquote>
            </aside>
            <p class='col-8'>Ut has elit labores, ex animal delectus efficiendi eos. Id soleat accusamus mel, sint deterruisset his an. Civibus fabellas interpretaris vis ea, dicat aperiri nec ut. Et posidonium dissentias ius, essent quodsi no nam. Mei graece prompta
              quaestio et, pri no voluptua atomorum. Pri id putant graecis. Autem prompta nostrud ut mei, mea ut facilisis expetenda intellegebat.</p>
          </div>
          <div class='row'>
            <p class='col-12'>Quo dolor commune albucius ea, ad novum senserit mediocritatem pro, te nisl quidam intellegam nam. Audire omittam in sea, per veniam noster ne. Duo illum assum discere ne, sed cu posse alterum accusam. Cum an error pertinacia, aperiam deleniti
              sedcu. Pri ut facilisi hendrerit reformidans, id qui modus libris deseruisse, cum primis moderatius ut.</p>
          </div>
        </article>
      </section>
    </main>
    <hr>
    <footer class='container'>
      <nav class='row'>
        <ul class='nav col-12'>
          <li><a href='#top'>HOME</a></li>
        </ul>
      </nav>
    </footer>
  </div>
  <!--End of #content-->
  <hr>
  <hr>
  <section id='a4' class='container'>
    <h2>Results</h2>
    <div class='container'>
      <div class='row'>
        <h3><code>textContent</code></h3>
        <div id='textContent' class='col-10'></div>
      </div>
      <hr>
      <div class='row'>
        <h3><code>innerText</code></h3>
        <div id='innerText' class='col-10'></div>
      </div>
    </div>
  </section>
  <script>
  </script>
</body>

</html>

答案 2 :(得分:0)

您所发布的代码不会调用validate函数,因此我将完全忽略它。您声明的目标确实不是很清楚,但是我将尝试遍历某些与您所拥有的类似的元素。

对于我的代码,我向所有未跳过的类添加了一个类;那是您进行处理的地方;调用函数等,例如el.classList.add("show-processors");

注意:skipList和功能filterBySkipCheck是此处的关键部分。

function doSomething(el) {
  const showplace = document.getElementById('actions-display')
    .getElementsByClassName('showme')[0];
  showplace.innerText = showplace.innerText + el.innerText;
  const textContentOutput = document.getElementById('textContentOutput');
  const innerTextOutput = document.getElementById('innerTextOutput');
  textContentOutput.innerHTML = el.textContent;
  innerTextOutput.innerHTML = el.innerText;
}

function hasParentWithMatchingSelector(target, selector) {
  return [...document.querySelectorAll(selector)].some(el =>
    el !== target && el.contains(target)
  );
}

function hasMatchingSelector(target, selector) {
  return [...document.querySelectorAll(selector)].some(el =>
    el === target
  );
}

function hasClass(element, classname) {
  return element.classList.contains(classname);;
}

function hasSelfOrParentWithClass(element, classname) {
  if (element.classList.contains(classname)) return true;
  return element.parentNode && hasSelfOrParentWithClass(element.parentNode, classname);
}

function hasParentWithClass(element, classname) {
  return hasParentWithMatchingSelector(element, '.' + classname);
}

function filterBySkipCheck(el, index, myarr, skipList) {
  let isSkipped = false;
  // process each item in skip list
  skipList.forEach(function(skip) {
    if (!isSkipped && skip.matchType === 'tag') {
      isSkipped = el.tagName === skip.match;
    }
    if (!isSkipped && skip.matchType === 'skipclass') {
      isSkipped = hasClass(el, skip.match);
    }
    if (!isSkipped && skip.matchType === 'selector') {
      isSkipped = hasMatchingSelector(el, skip.match);
    }
    if (!isSkipped && skip.matchType === 'parentselector') {
      isSkipped = hasParentWithMatchingSelector(el, skip.match);
    }
    if (!isSkipped && skip.matchType === 'element') {
      isSkipped = el === skip.match;
    }
  });
  return isSkipped;
}

function processAllElements(elements, skipL) {

  // filter for stuff to skip
  const filteredElements = [...elements].filter(function(el, index, myarr) {
    return filterBySkipCheck(el, index, myarr, skipL);
  });
  // this answers the question, how to process/loop through all but also how to filter
  for (let i = 0; i < elements.length; i += 1) {
    let el = elements[i];
    let isSkipped = filteredElements.includes(elements[i]);
    let shouldProcess = !isSkipped;
    if (shouldProcess) {
      el.classList.add("show-processors");
    }
  }
}

let skipList = [{
  match: "SECTION",
  matchType: "tag"
}, {
  match: "SCRIPT",
  matchType: "tag"
}, {
  match: "STYLE",
  matchType: "tag"
}, {
  match: "skipme-also",
  matchType: "skipclass"
}, {
  match: ".skipme",
  matchType: "selector"
}, {
  match: ".skipme",
  matchType: "parentselector"
}, {
  match: document.getElementById('second-skip'),
  matchType: "element"
}];

let elementsInScope = document.body.getElementsByTagName("*");
processAllElements(elementsInScope, skipList);
.show-processors {
  border: solid 1px red;
}

.show-skippers {
  border: solid 1px green;
}
<script>
  var myfriend = "pluto";
</script>
<div>first</div>
<div id='second-skip'>second</div>
<div>nested one
  <div>nested inner
    <div>nested granchild</div>
  </div>
</div>
<div>container for list
  <ul>in the list
    <li>one</li>
    <li>two</li>
    <li>three</li>
    <li>four</li>
  </ul>
</div>
<div><a href="#">testlink</a>
  <button type="button">button</button>
  <span>span1</span><span>spanner2</span>
</div>
<section>test section to skip</section>

<div class="skipme-also">I am skipped</div>
<div class="skipme">skip me by class</div>
<div>I contain paragraphs
  <p>Happy day</p>
  <p>Happy day2</p>
  <p>Happy day3</p>after paragraphs
</div>
<div id="actions-display" class="skipme">I just show stuff
  <button id="test-button" type="text">Click to test</button>
  <div class="showme"></div>
  <h3>Result of textContent:</h3>
  <textarea id="textContentOutput" rows="6" cols="30" readonly>...</textarea>
  <h3>Result of innerText:</h3>
  <textarea id="innerTextOutput" rows="6" cols="30" readonly>...</textarea> JavaScript
</div>