Replace certain html with other html using .html isn't working - javascript

I have this html
<div id="items-content">
<p><img class="fr-dib" src="http://i.imgur.com/bEDR9dc.png" data-imgslap="{{image-key}}" style="width: 214px;"></p>
</div>
And i want to replace src="http://i.imgur.com/bEDR9dc.png" with src="http://i.imgur.com/mJyABlG.jpg"
I have the following jquery
$(document).ready(function() {
$('#items-content').html( 'src="http://i.imgur.com/bEDR9dc.png"' ) {
return 'src="http://i.imgur.com/mJyABlG.jpg"';
}
} );
I'm learning JQuery still and I don't know where I have gone wrong. Would appreciate the help.
Update
I plan on using the same method of replacing the image to replace something like data-imgslap= with src=. Basically how do I replace html text 'x' with 'y' (They will only ever be html attributes text being replaced).

Use attr() to solve this problem
$(document).ready(function() { $('#items-content .fr-dib').attr('src', 'http://i.imgur.com/mJyABlG.jpg"'); } );
Or use regular expression
your_string.replace(/(<img\s class\=\"fr-dib\"\ssrc=")(.*?)("\s?\/>)/, "$1http://i.imgur.com/mJyABlG.jpg $3");

Update a DOM img tag's src
You're looking for jQuery's attr() method to update a single attribute's value:
$(document).ready(function() {
$('#items-content .fr-dib').attr('src', 'http://i.imgur.com/mJyABlG.jpg"');
} );
jsfiddle: https://jsfiddle.net/patrickberkeley/0wefe37t/
Update a DOM img src with a value from a data attr
To update one attribute with another attribute's value (in this example updating an image's src with a data attribute's value):
$(document).ready(function() {
var $img = $('#items-content [data-imgslap]');
var newSrc = $img.data('imgslap');
$img.attr('src', 'http://i.imgur.com/' + newSrc + '.jpg"');
} );
jsfiddle: https://jsfiddle.net/patrickberkeley/bx686410/2/
Regex to replace img src in a string
Based on the comments you've left though, it seems like your goal is to a value in a string (rather than updating an img element's src in the DOM).
In order to do that:
var str = '<div id="items-content"><p><img class="fr-dib" src="http://i.imgur.com/bEDR9dc.png" data-imgslap="mJyABlG" style="width: 214px;"></p></div>';
var newSrc = 'http://i.imgur.com/mJyABlG.png';
var newStr = str.replace(/<img(.*)src=[\"|\'](.*?)[\"|\'](.*)/, "<img$1src='" + newSrc + "'$3");
jsfiddle: https://jsfiddle.net/patrickberkeley/qrdt1esz/1/
Notice you *do not $(document).ready() because you're not selecting something from the dom. The above regex should handle: single and double quotes and any combination of attrs on either side of the img's src.

Related

jquery: tooltip is not displaying data after space

I am trying to show on mouse hover event data using jquery tool tip. have data like this way:
{"description":"marry christmas","date":"2016-12-25"}` that I got from server as JSON string. I am parsing that on my calendar like this way
holi is a variable name that holds above JSON string
this is my import
<link href = "https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css" rel = "stylesheet">
<script src = "https://code.jquery.com/jquery-1.10.2.js"></script>
<script src = "https://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
$.each(JSON.parse(holi), function(i, item) {
var holidayDate=item.date+"";
var parts= holidayDate.split("-");
alert("parts:"+parts[2]);
document.getElementById(parts[2]+parts[1]).style.color="green";
var va= document.getElementById(parts[2]+parts[1]).innerHTML;
document.getElementById(parts[2]+parts[1]).innerHTML="<label id="+parts[2]+parts[1]+" title="+
item.description+">"+va+"</label>";
$("#"+parts[2]+parts[1]).tooltip();
});
}
Now when I hover on 25th December it is just showing me marry instead of "marry christamas" I tried this in chrome. please let me what's wrong in this??
You need to add quotes around the title attribute value. Try this:
document.getElementById(parts[2]+parts[1]).innerHTML
="<label id="+parts[2]+parts[1]+" title='"+item.description+"'>"+va+"</label>";
Notice the single quotes after the = and before the > around your item.description variable.
Also, as others have pointed out, avoid writing out the DOM from javascript. It is error prone and hard to maintain.
When constructing the title HTML, you need to take into account how the HTML will be parsed. If your title message has spaces, then the HTML attribute value has to be quoted.
You could clean up your code a lot by leveraging the jQuery APIs, since you're already using the library:
$.each(JSON.parse(holi), function(i, item) {
var holidayDate = item.date + "";
var parts = holidayDate.split("-");
var dayId = parts[2] + parts[1], day = $("#" + dayId);
day.css("color", "green")
.html($("<label/>", {
title: item.description,
html: day.html()
}))
.find("label").tooltip();
});
With jQuery, you can construct new HTML with less ugly quote-wrangling by using the form
$("<tagname/>" {
attribute: value,
attribute: value,
// ...
})
In this case, the code sets the "title" attribute and then the content; the "html" attribute works like the jQuery .html() method.
After that, it finds the just-added <label> element and invokes the .tooltip() method.

Insert HTML after certain paragraph of HTML string

I've got a HTML-string I'd like to render but append some HTML after the 2nd paragraph first.
function insertStuff() {
//var string = "<div><p>paragraph 1</p><p>paragraph 2</p><p>paragraph 3</p></div>"; works
var string = '<p><img src="http://example.com/my-cool-picture.png" alt="alt text"></p><p>2nd paragraph</p><p>3rd paragrpah</p>' // doesn't work
var parsedHtml = $(string)
parsedHtml.find("p:nth-child(2)").after("<p>My cool insert</p>")
return parsedHtml.html()
}
This works for the HTML string above but the following one only return the <img> after invoking parsedHtml.html()
What am I doing wrong?
Since you are use .html() it will return html of first element.
You can wrap your content in a div like
var parsedHtml = $('<div />').html(string)
Then your code will work.
function insertStuff() {
var string = '<p><img src="http://example.com/my-cool-picture.png" alt="alt text"></p><p>2nd paragraph</p><p>3rd paragrpah</p>'
var parsedHtml = $('<div />').html(string)
parsedHtml.find("p:nth-child(2)").after("<p>My cool insert</p>")
return parsedHtml.html()
}
alert(insertStuff())
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Try this
function insertStuff() {
var string = '<div><p><img src="http://example.com/my-cool-picture.png" alt="alt text"></p><p>2nd paragraph</p><p>3rd paragrpah</p></div>';
var parsedHtml = $(string)
parsedHtml.find("p:nth-child(2)").after("<p>My cool insert</p>")
return parsedHtml.html()
}
You should put this string in a div as parent.
That's because html method as getter returns html content of the first element in the set. You should either wrap all the top-level elements in the set with another element and read it's html content or iterate through the set and concatenate each element's outerHTML property.
parsedHtml.map(function() { return this.outerHTML; }).get().join('');
If you want to get the innerHTML of all the elements in the set, replace outerHTML with innerHTML.
when you use find() with a selector it will search inside that selector (in child nodes) that why when you use string with div tag you are getting the desired result and when you delete div the problem occured

How to search specific attribute within a tag and remove it using javascript regex

Basically I have this kind of tag (just for example)
<div type="text" onclick="event();" onblur="event();">this div has onclick and onblur functions</div>
and I want to remove some attributes to that tag using a reference variable.
var refAttribs = ['onclick', 'onblur'];
So it should strip out all attributes from refAttribs.
Be careful not to strip out the content of the div. Because it also contains a string from the refAttribs variable.
How do I get rid of them using a regex?
Thanks in advance
As you've stated the tag is a string then you could santise it with the following javascript.
var refAttribs = ['onclick', 'onblur'];
function remove(tagToClean)
{
var result = tagToClean;
for(var i=0; i<refAttribs.length; i++)
{
regex = new RegExp(refAttribs[i] + "=\"[a-zA-Z\(\);]*?\"", "g");
result = result.replace(regex, "");
}
return result;
}
You can call the method by passing in your string.
remove('<div type="text" onclick="event();" onblur="event();">this div has onclick and onblur functions</div>');
I'm not 100% sure what you're trying to do here. Are you trying to modify the DOM? If so you will need to modify the method to accept a handle to a DOM node. A little more information would help.
Well, try this:
To remove onclick, the regex will be:
(<[^>]+)\s+onclick\s*=[\'"].*?[\'"]
Debuggex Demo
The removeAttr function:
function removeAttr(html, attr) {
return html.replace(new RegExp('(<[^>]+)\\s+' + attr + '\\s*=[\'"].*?[\'"]', 'gi'), '$1');
}
http://jsfiddle.net/rooseve/pC4aH/1/

Alternative writing method to create DOM elements and append

If I want to append a button with my pic to the document, I would write:
$('#story_pages').append('<div><button value="'+window_value+'" onclick="reload_to_canvas(this.value)" > <img id= "w'+window_value+'", src="../pic/white_img.png", width="110px", height="110px"/> </button></div>');
It's too long and hard to debug. But how can I create an img tag, then wrapping it with a button tag and div tag...
Please suggest any clear and simple method with jQuery's help.
UPDATE:
story_pages is the jQuery UI dialog's id. I don't know if it affects or not.
UPDATE:
I found the problem. I want the image shown above on the button instead of a button and a image.
The script you give me will result this:
<div>
<button value="1"></button>
<img ......./>
</div>
The img tag has to be wrapped by button tag like:
<button>
<img.../>
</button>
So the image will attach on the button.
How about this:
var $button = $('<button>', {
value: window_value,
click: function() { reload_to_canvas(this.value); }
});
var $img = $('<img>', {
id : 'w'+ window_value,
src: '../pic/white_img.png'
})
.css({ height: '100px', width: '100px'});
$('#story_pages').append($('<div>').append($button, $img));
If a string is passed as the parameter to $(), jQuery examines the string to see if it looks like HTML (i.e., it starts with ). If not, the string is interpreted as a selector expression, as explained above. But if the string appears to be an HTML snippet, jQuery attempts to create new DOM elements as described by the HTML. Then a jQuery object is created and returned that refers to these elements.
try this
var div=$('<div>'); // creates new div element
//updated here
var img = $('<img />') .attr({ // create new img elementand adds the mentioned attr
id:'w'+window_value ,
src:"../pic/white_img.png",
width:"110px",
height:"110px"});
var button= $('<button/>', //creates new button
{
value: window_value, //add text to button
click: function(){ reload_to_canvas(this.value)} //and the click event
}).html(img); /// and <-- here... pushed the created img to buttons html
div.append(button); //append button ,img to div
$('#story_pages').append(div); //finally appends div to the selector
updated example fiddle
$('#story_pages').append(
$('<div>').append(
$('<button>', {
value : window_value
}).click(function() {
reload_to_canvas(this.value);
}).append(
$('<img>', {
id : 'w' + window_value,
src : '../pic/white_img.png'
}).width(110)
.height(110)
)
)
);

How to use jquery to remove extra whitespace before content in <textarea> without changing html

I want to use jquery append() to add content to a textbox without having to consider newline characters that show up in the html markup and indent the content. How do I get jquery to ignore newline characters in regards to textarea?
<div id = "content-frame">
<div id = "remove-frame">
<div id = "content">
here is the content, click this content
</div>
</div>
</div>
$("#remove-frame").click(function () {
var divContents = $("#content").text();
$("#content").remove();
$("#remove-frame").append(function() {
return '<textarea id = "edit-textarea">' + divContents + "</textarea>";
});
});
http://jsfiddle.net/8KA8q/3/
You missed to trim the content value. Also you can use JQuery.trim() to keep browser compatibility. Try to modify your code as bellow:
$("#remove-frame").click(function () {
var divContents = $("#content").text().trim();
$("#content").remove();
$("#remove-frame").append(function() {
return '<textarea id = "edit-textarea">' + divContents + "</textarea>";
});
});
I think what you want is .prepend() instead of .append();
append places it as a last child, prepend as a first child.
also if that doesnt work play with .appendto() and .prependto().
Good luck
Take a Look

Categories