2

I have such a code:

<!DOCTYPE html>
<html>
<body>

<button onclick="myFunction()">Click me</button>

<table class="demo">
    <div>
        <a>link1</a>
        <p>text</p>
    </div>
</table>

<a>link2</a>

<script>
function myFunction() {
    var el = document.getElementsByClassName("demo")[0].getElementsByTagName("a");
    for (var i = 0; i < el.length; i++) {
        el[i].style.color = "red";
 }
}
</script>

</body>
</html>

I would like to change only these links which are inside the table. Is it possible using js? How to do this?

1
  • Suggest using document.querySelectorAll('table.demo a'); to get all your links. Commented Jun 24, 2015 at 11:49

3 Answers 3

1

Your html is invalid, div can't be a child of table.

Since you are not using any table constructs change the table to div

function myFunction() {
  var el = document.getElementsByClassName("demo")[0].getElementsByTagName("a");
  for (var i = 0; i < el.length; i++) {
    el[i].style.color = "red";
  }

}
<button onclick="myFunction()">Click me</button>
<div class="demo">
  <div>
    <a>link1</a>
    <p>text</p>
  </div>
</div>
<a>link2</a>

The html rendered when using markup is as shown in the below image, if you look at it the div is rendered outside of the table

enter image description here

Sign up to request clarification or add additional context in comments.

Comments

0

Actually, a div can be inside a td tag.

<!DOCTYPE html>
<html>
<body>

<button onclick="myFunction()">Click me</button>

<table class="demo">
<tr>
<td>
<div>
<a>link1</a>
<p>text</b>
</div>
</td>
</tr>
</table>
<a>link2</a>

<script>
function myFunction() {
  var el = document.getElementsByClassName("demo")[0].getElementsByTagName("a");
  for (var i = 0; i < el.length; i++) {
      el[i].style.color = "red";
 }

}
</script>

</body>
</html>

It works then. IBM Websphere Portal uses such a construction.

Comments

0

You should make use of span tag.

<!DOCTYPE html>
<html>
<body>

<button onclick="myFunction()">Click me</button>

<table class="demo">
<tr>
<td>
<div>
<a><span id="link1">link1</span></a>
<p>text</b>
</div>
</td>
</tr>
</table>
<a>link2</a>

<script>
function myFunction() {
    document.getElementById("link1").innerHTML="abcd";

 }
</script>

</body>
</html>

The button click will change the link using js. You can do any kind of css changes using the id of span. Kindly upvote if this solves your query.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.