Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change HTML attributes in a raw string with Jquery or Javascript?

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.'
like image 520
adrianmc Avatar asked Aug 01 '15 22:08

adrianmc


People also ask

Can Javascript change HTML attributes?

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.

What are the methods used in jQuery to change and manipulate HTML elements and attributes?

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.

What is parseHTML in JavaScript?

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).

How do I escape HTML data?

To escape data for an HTML Attribute, use Laminas\Escaper\Escaper 's escapeHtmlAttr() method.


1 Answers

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();
like image 144
charlietfl Avatar answered Nov 11 '22 03:11

charlietfl