I'm trying to get a link to wrap around all text within a div. I can only find solutions where you move certain DOM elements entirely, or move other elements into an element.
current situation:
<div class="text">
<a href="link">text</a> and more text
</div>
desired situation:
<div class="text">
<a href="link">text and more text</a>
</div>
Unfortunately, I cannot change the markup, so I have to do something with jQuery.
An HTML element is defined by a starting tag. If the element contains other content, it ends with a closing tag. For example, <p> is starting tag of a paragraph and </p> is closing tag of the same paragraph but <p>This is paragraph</p> is a paragraph element.
Closing tags are the tags in HTML that need to be closed. These have a starting tag and an ending tag. The ending tag is the closing tag. For example, the opening tag for the paragraph tag is <p> and the closing tag is </p>.
No. HTML 4. x doesn't have any concept of self closing tags.
Avoid messing with html directly, it's better not to change it or overwrite. All you need to do is to take next text sibling Node and append to previous a
:
$('.text a').each(function() {
$(this).append(this.nextSibling)
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="text">
<a href="link">text</a> and more text
</div>
If necessary you can check for the next node to be TextNode, if you need to skip element nodes:
if (this.nextSibling.nodeType === 3) {
$(this).append(this.nextSibling)
}
You need to use .append( function )
to insert nextSibling
of anchor into it.
$(".text a").append(function(){
return this.nextSibling
});
$(".text a").append(function(){
return this.nextSibling
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="text">
<a href="link">text</a> and more text
</div>
Also you can use .html( function )
instead and then remove next sibling using .remove()
$(".text a").html(function(i, h){
return h + this.nextSibling.nodeValue;
})[0].nextSibling.remove();
Or in one line using ES6
$(".text a").html((i,h) => h+this.nextSibling.nodeValue)[0].nextSibling.remove();
$(".text a").html(function(i, h){
return h + this.nextSibling.nodeValue;
})[0].nextSibling.remove();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="text">
<a href="link">text</a> and more text
</div>
Or using pure javascript
var ele = document.querySelector(".text a");
ele.innerHTML += ele.nextSibling.nodeValue;
ele.nextSibling.remove();
var ele = document.querySelector(".text a");
ele.innerHTML += ele.nextSibling.nodeValue;
ele.nextSibling.remove();
<div class="text">
<a href="link">text</a> and more text
</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With