skip to Main Content

I need to set all of the content in a certain <div> to open to another tab ( target="_blank").
I don’t really care how this is solved, you can use JS, CSS, HTML, classes, IDs, et cetera.

I tried using <base target="_blank"> but it covered everything no matter what rather than just a certain area.
Example:
<a href="example.html"> <div> <base target="_blank"> [CONTENT] </div>
I thought that example.html would be opened in the same tab, but its target is set to "_blank" as well.

I also tried doing <div target="_blank"> but it didn’t make any effect, instead it was treated as a normal <div>.

2

Answers


  1. Chosen as BEST ANSWER

    Add a class to <div> elements which must have <a> elements with blank targets, then use the CSS selector .target_blank a to locate all <a> elements that are children of an element with the class. You can loop over them and set the .target property. Code is shown below:

    `const target_blank = document.querySelectorAll('.target_blank a');
    for (const el of target_blank) {
      el.target = "_blank";
    }
    
    <div class="target_blank">
      <a href="https://example.com" id="test1">Test 1</a>
      <div>
        <a href="https://example.com">Test 2</a>
      </div>
    </div>
    
    <a href="https://example.com" id="test3">Test 3</a>
    <a href="https://example.com">Test 4</a>`
    

  2. You can simply add a class to the <div> elements whose <a> element must get target="_blank", then use the CSS selector .target_blank a to get all <a> elements that are children of an element with that class. From there you can just loop over them and set the .target property:

    const target_blank = document.querySelectorAll('.target_blank a');
    for (const el of target_blank) {
      el.target = "_blank";
    }
    <div class="target_blank">
      <a href="https://example.com" id="test1">Test 1</a>
      <div>
        <a href="https://example.com">Test 2</a>
      </div>
    </div>
    
    <a href="https://example.com" id="test3">Test 3</a>
    <a href="https://example.com">Test 4</a>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search