Applying links via JavaScript - javascript

Hullo, I am wondering how I can add a new link around/to an element, using only JavaScript? I am new to JavaScript, and I am sorry if this question seems stupid or too easy.
Current:
<div class="container">
<div class="content1"></div>
<div class="content2"></div>
</div>
Desired Code:
<div class="container">
<div class="content1"></div>
<a href="http://example.com">
<div class="content2"></div>
</a>
</div>

Just use normal DOM manipulation, nothing tricky required
const container = document.querySelector('.container');
const a = container.appendChild(document.createElement('a'));
a.href = "http://example.com";
a.appendChild(document.querySelector('.content2'));
console.log(container.innerHTML);
<div class="container">
<div class="content1"></div>
<div class="content2"></div>
</div>

Can use jQuery wrap()
$('.content2').wrap('<a href="http://example.com">')
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div class="content1">content 1</div>
<div class="content2">content 2</div>
</div>

Create a new a element and create a child in that element with the same content in your div and append the a element in the parent of the old div('.container')
var content2 = document.getElementsByClassName('content2')[0];
var container = content2.parentNode;
var a = document.createElement('a');
a.setAttribute("href", "www.google.com");
container.replaceChild(a, content2);
a.appendChild(content2);
<div class="container">
<div class="content1">Content1</div>
<div class="content2">Content2</div>
</div>

Using only pure Javascript, you can do something like this:
1. get your div by class (you can do using getElementById if you define an id for your div)
var mydiv = document.getElementsByClassName('content1');
2. create your anchor and set an href
var new_anchor = document.createElement("a");
new_anchor.href = "http://example.com";
3. Place the div content1 inside new anchor
new_anchor.append(mydiv[0]);
4. Place your entire element inside the container again
var mycontainer = document.getElementsByClassName('container');
mycontainer[0].insertBefore(new_anchor, mycontainer[0].childNodes[0])

Related

How to insert html elements

I'm trying to insert the whole element into the container element however It throws some object into the DOM
JS:
const CONTAINER = document.getElementById('container');
let title = document.querySelector('h1').cloneNode(true);
CONTAINER.insertAdjacentHTML('beforeend', title);
HTML:
<div class="container" id="container"></div>
<h1>Test</h1>
Or, as a one-liner:
document.getElementById('container').insertAdjacentHTML('beforeend', document.querySelector('h1').outerHTML);
<div class="container" id="container">This is the target container</div>
<p>Some padding text</p>
<h1>Test</h1>
title it is an HTMLElementObject. Use appendChild instead.
const CONTAINER = document.getElementById('container');
let title = document.querySelector('h1').cloneNode(true);
CONTAINER.appendChild(title);
<div class="container" id="container"></div>
<h1>Test</h1>

How to wrap a group of sibling elements within a containing div using Vanilla JS?

I have the following HTML:
<div class="container">
<h1 class="heading">heading</h1>
<p class="paragraph">test</p>
<h2 class="subheading">123</h2>
<a class="link">321</a>
</div>
How can I wrap the last three elements within .container, so that the output looks like this:
<div class="container">
<h1 class="heading">heading</h1>
<div class="subcontainer">
<p class="paragraph">test</p>
<h2 class="subheading">123</h2>
<a class="link">321</a>
</div>
</div>
It would be better to do it within the HTML, but in case due to some constraints that you can't modify the HTML, you can do the followings
const container = document.querySelector('.container');
const subcontainer = document.createElement('div');
const lastThree = Array.from(container.children).slice(-3);
subcontainer.classList.add('subcontainer');
// move the elements into the subcontainer
lastThree.forEach(node => {
subcontainer.appendChild(node);
});
container.appendChild(subcontainer);
<div class="container">
<h1 class="heading">heading</h1>
<p class="paragraph">test</p>
<h2 class="subheading">123</h2>
<a class="link">321</a>
</div>
The class name container is quite generic, make sure that you only select the container element you want, or else you might modify other elements unintentionally.
old_html = document.getElementsByClassName("container")[0];
firstChild = old_html.children[0];
old_html.removeChild(firstChild);
new_html = "<div class='container'>"+ firstChild.outerHTML + "<div class = 'subcontainer'>" + old_html.innerHTML + "</div></div>";
console.log(new_html);
<div class="container">
<h1 class="heading">heading</h1>
<p class="paragraph">test</p>
<h2 class="subheading">123</h2>
<a class="link">321</a>
</div>

How to retrieve the div first child element sibling node using querySelector?

I have the DOM structure like below
<div class="table_body">
<div class="table_row">
<div class="table_cell">first</div>
<div class="table_cell">chocolate products</div><!-- want to access this div content -->
</div>
<div class="table_row">
<div class="table_cell">third</div>
<div class="table_cell">fourth</div>
</div>
</div>
From the above HTML I want to access the div content of second div with classname table_cell inside first table_row div.
So basically I want to retrieve the content of div with classname table_cell with content chocolate products.
I have tried to do it like below
const element = document.querySelector('.rdt_TableBody');
const element1 = element.querySelectorAll('.rdt_TableRow')[0]
const element2 = element1.querySelectorAll('.rdt_TableCell')[0].innerHTML;
When I log element2 value it gives some strange output and not the text "chocolate products"
Could someone help me how to fix this. Thanks.
You can use:
the :nth-of-type pseudo-selector
combined with the immediate-child selector (>)
Example:
const selectedDiv = document.querySelector('.table_body > div:nth-of-type(1) > div:nth-of-type(2)');
Working Example:
const selectedDiv = document.querySelector('.table_body > div:nth-of-type(1) > div:nth-of-type(2)');
selectedDiv.style.color = 'white';
selectedDiv.style.backgroundColor = 'red';
<div class="table_body">
<div class="table_row">
<div class="table_cell">first</div>
<div class="table_cell">chocolate products</div> //want to access this div content
</div>
<div class="table_row">
<div class="table_cell">third</div>
<div class="table_cell">fourth</div>
</div>
</div>
In your code
element1.querySelectorAll('.table_cell')[0], this is targeting the first element i.e., <div class="table_cell">first</div>. That's the reason why you are not getting the expected output.
I have made it to element1.querySelectorAll('.table_cell')[1], so that it'll target <div class="table_cell">chocolate products</div>.
const element = document.querySelector('.table_body');
const element1 = element.querySelectorAll('.table_row')[0]
const element2 = element1.querySelectorAll('.table_cell')[1].innerHTML;
console.log(element2);
<div class="table_body">
<div class="table_row">
<div class="table_cell">first</div>
<div class="table_cell">chocolate products</div>
</div>
<div class="table_row">
<div class="table_cell">third</div>
<div class="table_cell">fourth</div>
</div>
</div>
Since the element that you want to target is the last div with having class table_cell, you can use :last-of-type on table_cell class using document.querySelector. But otherwise you can also use :nth-of-type if there are more than 2 elements and you want to target any element in between first and last.
Below is the example using :last-of-type.
const elem = document.querySelector(".table_row > .table_cell:last-of-type");
console.log(elem?.innerHTML);
<div class="table_body">
<div class="table_row">
<div class="table_cell">first</div>
<div class="table_cell">chocolate products</div> //want to access this div content
</div>
<div class="table_row">
<div class="table_cell">third</div>
<div class="table_cell">fourth</div>
</div>
</div>
For more info you can refer :nth-of-type, :last-of-type and child combinator(>).

How to trigger a click on an element in javascript

I have the following Html:
<div class="box-row">
<div class="box c2-3">
<div class="box-overlay"></div>
<div class="box-letter"></div>
</div>
<div class="box c2-4">
<div class="box-overlay"></div>
<div class="box-letter"></div>
</div>
<div class="box c2-5">
<div class="box-overlay"></div>
<div class="box-letter"></div>
</div>
<div class="box c2-6 trr">
<div class="box-overlay trr"></div>
<div class="box-letter"></div>
</div>
</div>
I want to randomly select one of the elements with class: c2-3, c2-4, c2-5, c2-6 and trigger a click.
This is the code I have thus far:
var map = [
'c2-3', 'c2-4', 'c2-5', 'c2-6',
];
var x = Math.floor((Math.random() * 4));
var element = document.getElementsByClassName(map[x]);
At this point I want to trigger the click and am unsure how to do it:
element.trigger('click'); ??
Use element.click(); instead of element.trigger('click'); but also, you need to either get only a single element, or loop over the returned HTMLCollection from .getElementsByClassName().
For example, to loop:
var elements = document.getElementsByClassName(map[x])
elements.forEach(element => element.click())
...Or, to get a single element (still using getElementsByClassName):
var element = document.getElementsByClassName(map[x])[0]
element.click()
Alternatively, you can use querySelector:
var element = document.querySelector(`.${map[x]}`)
element.click()

How can I Target parent and child class I javascript

<div id="inst4" class="block_navigation block">
<div class="content">
<div> Content Start here !!!</div>
</div>
</div>
<script>
var blockNav = document.getElementsByClassName("block_navigation")[0].getElementsByClassName("content");
blockNavIcon = document.createElement("img");
blockNavIcon.setAttribute("src", blockIcon);
blockNav.appendChild(blockNavIcon);
}
</script>
Here I am targeting content class, but it is not working, How can i do this any solution.
There are few problems in your script, you are using the class block_navigation twice, also blockNav is a NodeList
You can easily use .querySelector()
var blockNav = document.querySelector(".block_navigation .content");
blockNavIcon = document.createElement("img");
blockNavIcon.setAttribute("src", '//placehold.it/64');
blockNav.appendChild(blockNavIcon);
<div id="inst4" class="block_navigation block">
<div class="content">
<div>Content Start here !!!</div>
</div>
</div>
You can use use .getElementsByClassName("content")[0]
Hope this wil be helpful
var blockIcon = "http://weknowyourdreams.com/images/forest/forest-04.jpg";
var blockNav = document.getElementsByClassName("block_navigation")[0]
.getElementsByClassName("content")[0]; // Will select the child element
blockNavIcon = document.createElement("img");
blockNavIcon.setAttribute("src", blockIcon);
blockNav.appendChild(blockNavIcon)
JSFIDDLE

Categories

Resources