Josh Boothe
Josh Boothe

Reputation: 1423

Javascript .replace new line within search string (not targeting?)

I have written this quick but of code:

var navTitle = $('#nav ul').html();
    var replacer = navTitle.replace('<li class="page_item page-item-73">
    <a href="xxx/">x training programme</a><ul class=\'children\'>', 
    '<li class="page_item page-item-73"><a href="xxx/">x training programme</a
    <ul id="longDropdown" class=\'children\'>');
    console.log(replacer);
    //$('#nav ul').html(replacer);

In the HTML it appears like this:

<li class="page_item page-item-73"><a href="xxx/">x training programme</a>
<ul class='children'>

I tried putting a \n after the in the search string however the string is not changing, I think it cannot find the src string.

Is the issue here the new line? I believe so however cannot target it.

Upvotes: 0

Views: 93

Answers (2)

jAndy
jAndy

Reputation: 236002

jQuery offers the .replaceWith() and .replaceAll methods.

$('#nav ul .page_item.page-item-73 a').replaceWith('<a href="xxx/"x training programme</a>');

Maybe even changing the text content or inner HTML will do for you

$('#nav ul .page_item.page-item-73 a').text('x training programme');

respectively

$('#nav ul .page_item.page-item-73 a').html('x training programme');

Upvotes: 1

ChrisIPowell
ChrisIPowell

Reputation: 494

Why don't you just select the ul and then use .attr to add the ID?

var navTitle = $('#nav ul ul.children').attr('id', 'longdropdown');

Manipulating the DOM tends to be a lot tidier and safer than doing string replaces.

Upvotes: 0

Related Questions