1

First of all, there are alot similar questions outside not only on this website.

But I searched at least 3 hours for a solution but never found something that was fitting and working.

Also some threads where created long time ago, so some solutions are more complicated/not working and dont use todays possibilities.


So here's the Problem:

HTML File could look like this:

<ul>
  <li><a class="content" href="this.com">I should change!</a>
  </li>
  <li><a class="content" href="any.com">I don't change</a>
  </li>
  <li><a class="content" href="this.com">I should change! too</a>
  </li>
  <li><a class="content" href="any.com">I don't change</a>
  </li>
  <li><a class="content" href="this.com">I also should change!</a>
  </li>
</ul>

Now I want to get all elements wich have attribute class="content".

(I tried solutions with document.getElementsByClassName() and document.querySelector().)

And then change only those wich also contain href="this.com".


And here are the "challenges" the solution should pass:

  • no jQuery and co. -> pure javascript

  • you can only use javascript (the whole solution should work by injecting script.js into a website)

  • if it is possible: no loops

I don't want to make it more complicated than it should be, just thougth that there must be a way to change multiple objects easily like this just for classes:

document.getElementById("theID").innerHTML = "text"

So if there is any way to make it without loop it would be great

(saw alot of solutions with some counting funtion "i < variable.length; i++" when it comes to loop-solution. But think it's much cleaner with simple function like .innerHTML = "" than running a loop)

  • And last: if you know how I could easily delete <li></li> of the selected objects and would tell me know, I would be very thankful.

(I know .parentNode but if I try with this it's more an "Error and Retry Adventure")

Also have trouble with deleting parent of parent or could I just use .parentNode.parentNode ?


If anyone has an idea or working solution I would be very happy.

Thank you very much!

VVind0wM4ker
  • 13
  • 1
  • 5
  • Firstly, what didn't work about `getElementsByClassName`? Second, _if it is possible: no loops_ - EH? – Rhumborl Nov 18 '14 at 11:48
  • If you want to act on more than one element, you'll need a loop (or a function which internally uses a loop). The example you gave of not needing a loop (by using `getElementById` and `innerHTML`) only acts on a single element. – Shai Nov 18 '14 at 11:52
  • One question/observation: If you unwrap the selected elements by removing the `
  • ` it becomes invalid html. a `
      ` should have `
    • ` children.
  • – Jamiec Nov 18 '14 at 12:52