I want to take a bunch of anchor tags and make sure that they all open in a new tab.
I know I should do something like this $('a').attr('target', '_blank');
but the catch is that the HTML I am trying to modify is in a string variable.
See example:
I have a bunch of raw HTML in a string like this:
var rawHTML = 'Hello there, <a href="http://www.google.com">this</a> is a link.'
How can I convert that to be something like this:
processedHTML = 'Hello there, <a href="http://www.google.com" target="_blank">this</a> is a link.'
Javascript can be used to change the attribute(s) of a HTML element, such as a paragraph, a header, an image, or a list, or any various HTML elements. For example, by changing the src attribute of an img tag, we can change the image entirely to something else with Javascript.
Three simple, but useful, jQuery methods for DOM manipulation are: text() - Sets or returns the text content of selected elements. html() - Sets or returns the content of selected elements (including HTML markup) val() - Sets or returns the value of form fields.
parseHTML uses native methods to convert the string to a set of DOM nodes, which can then be inserted into the document. These methods do render all trailing or leading text (even if that's just whitespace).
To escape data for an HTML Attribute, use Laminas\Escaper\Escaper 's escapeHtmlAttr() method.
Using jQuery you can append the string to an element outside of the DOM
You can then use jQuery methods on this new element to modify the html and then return the modified string:
var rawHTML = 'Hello there, <a href="http://www.google.com">this</a> is a link.';
// create element and set string as it's content
var $div = $('<div>').html(rawHTML);
// modify attributes
$div.find('a').attr('target', '_blank');
// return modified content to string
var processedHTML = $div.html();
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