Sai Revanth
Sai Revanth

Reputation: 37

How can we change the value of a p tag present in v2 div?

How can we change the value of a p tag present in v2 div?

<div id="v1">
<div id="flow">
    <p id="content">Hello</p>
</div>
</div>
<div id="v2">
<div id="flow">
    <p id="content">Hello</p>
</div>
</div>

Upvotes: 1

Views: 73

Answers (5)

Ashikur Rahman
Ashikur Rahman

Reputation: 78

<div id="v1">
<div id="flow">
    <p id="content">Hello</p>
</div>
</div>
<div id="v2">
<div id="flow">
    <p id="content">Hello</p>
</div>
</div>

This will be work for all the p and nested p inside v2 div.

   <script>
traverse=(node)=>{
      for(let i=0;i<node.childElementCount;i++){
          if(node.children[i].nodeName=="p"){
            node.children[i].innerHTML=`Your HTML`;
          }
          if(node.children[i].childElementCount>0)
          {
              traverse(node.children[i]);
          }

      }
    }
    traverse(document.getElementById("v2"));
</script>

Upvotes: 0

Mohammad Usman
Mohammad Usman

Reputation: 39342

  • First of all, remove duplicate ids from your code. No two elements withing a page should have same id. You may use class attribute if you wants to have multiple elements in same group. See this post for more details.
  • Second, use querySelector() method to get a reference to the desired element and override its textContent property with the content you wants to add.

let para = document.querySelector('#v2 p.content');

para.textContent = 'World';
<div id="v1">
  <div class="flow">
      <p class="content">Hello</p>
  </div>
</div>
<div id="v2">
  <div class="flow">
      <p class="content">Hello</p>
  </div>
</div>

References:

Upvotes: 0

Jack Bashford
Jack Bashford

Reputation: 44125

It is invalid syntax and as such generally advised against to have multiple uses of the one ID on a page, but here is how you’d do it:

<div id="v1">
    <div id="flow">
        <p id="content">Hello</p>
    </div>
</div>
<div id="v2">
    <div id="flow">
        <p id="content">Hello</p>
    </div>
</div>
document.getElementById("v2").getElementById("content").innerText = "Some new text";

Upvotes: 0

לבני מלכה
לבני מלכה

Reputation: 16251

Use unique id to each p and change between innerHTML

var c1=document.getElementById("content1").innerHTML;
var c2=document.getElementById("content2").innerHTML;

document.getElementById("content1").innerHTML = c2;
document.getElementById("content2").innerHTML = c1;
<div id="v1">
<div class="flow">
    <p id="content1">Hello</p>
</div>
</div>
<div id="v2">
<div class="flow">
    <p id="content2">Hello of 2</p>
</div>
</div>

Upvotes: 1

Bibberty
Bibberty

Reputation: 4768

Here. And yes ID should be unique.

document.querySelector('#v2 div p').innerHTML = 'changed';
<div id="v1">
<div id="flow">
    <p id="content">Hello</p>
</div>
</div>
<div id="v2">
<div id="flow">
    <p id="content">Hello</p>
</div>
</div>

Upvotes: 0

Related Questions