accessing nextElementSibling in HTML - javascript

I have written a lightbox script in plain JS:
HTML:
<img onclick="pLightbox(this)" src="MyPhoto.jpg" />
JS:
function pLightbox(objPhoto){
var path=objPhoto.src;
HTMLtext = '<img src="' + path + '">';
containerDiv.innerHTML = HTMLtext;
}
(code abbreviated for clarity)
This works fine. Now I'm trying to access the next sibling within the DIV. I have tried:
HTMLtext += '<img src="images/Next.png" onclick="pLightbox(' + objPhoto.nextElementSibling + ')">';
This doesn't work - Tried several different variations (nextElementSibling.src, etc.) , but nothing works.
How do I access the next sibling from an HTML string?

Eh, no. Do not concatenate DOM elements with strings. Do not use event handlers. Especially, do not use event handler content attributes.
This is the proper way. No events in HTML. No nasty string manipulation. No HTML injection vulnerabilities.
document.querySelector('img').addEventListener('click', pLightbox);
function pLightbox() {
containerDiv.innerHTML = "";
var img = document.createElement('img');
img.src = this.src;
img.addEventListener('click', pLightbox.bind(this.nextElementSibling));
containerDiv.appendChild(img);
}
<img src="//stackoverflow.com/favicon.ico" />
<img src="//scifi.stackexchange.com/favicon.ico" />
<img src="//superuser.com/favicon.ico" />
<img src="//crossvalidated.com/favicon.ico" />
<div id="containerDiv">Click the first image. Then keep clicking the new image</div>

Related

Fetch and add img attributes to string

I have a string like this.
x = '<div class="sample">
<img src="http://www.example.com/i/java.png">
</div>
<div class="sample_another">
<img src="/i/somedir/python.png">
</div>'
I want to convert to this
x = '<div class="sample">
<img src="http://www.example.com/i/java.png" height="200px" width="100px">
</div>
<div class="sample_another">
<img src="/i/somedir/python.png" width="150px" height="150px">
</div>'
input string will be a html doc. for all the images in the doc, i want to add the height and width property. and to get the height and width property i have to use something like this
var img = new Image();
img.onload = function() {
alert(this.width + 'x' + this.height);
}
img.src = 'http://www.example.com/intl/logo.gif';
p.s. i tried using this solution but the problem i face is that the string might have the script tag and DOM parses it as a closing script tag. I cant find much for regex either. So is there any other way to obtain this result ?
Thanks.
If you can remove scripts than go with this code:
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
var string ="<script type"text/javascript"></script><img alt=''
src='http://api.com/images/UID' /><br/>Some plain text<br/><a
href='http://www.google.com'>http://www.google.com</a>";
var elem= document.createElement("div");
$(string).find('script').remove();
elem.innerHTML = string;
var images = elem.getElementsByTagName("img");
for(i=0; i<images.length; i++){
images[i].width = "150";
images[i].height = "250";
}
string = elem.innerHTML;
Problem you are facing with is that it turns out that HTML5 does not allow script tags to be dynamically added using the innerHTML property. So you will need to add them dynamically on some other way.
This is some code that might help you:
var my_awesome_script = document.createElement('script');
my_awesome_script.setAttribute('src','http://example.com/site.js');
document.head.appendChild(my_awesome_script);

Find a element and append a image

I know how to append a image to a known tag. e.g.
//html
<div class="ImageContainer"></div>
//JS
var image = new Image;
image.src = '/Public/Images/image.png';
image.appendTo($('.ImageContainer'));
but how to find a certain tag(the figure tag here) and append the image?
I could locate the figure tag with '.find()':
var ImageContainer = $('<div><figure></figure></div>').
console.log(ImageContainer.find('figure').html());
but failed to append the image to it:
image.appendTo(ImageContainer.find('figure')); //doesn't work
If you have an image element with an id you can select it like so:
var $image = '<img src="/Public/Images/image.png" />';
Then so find the figure elemnt:
$(ImageContainer).find('figure').append($image);
Try below code.
1) Stored image url in variable name $img.
2) Find the div using class name 'image' ($('.image'))
3) Appended image to div
HTML
<div class="image"> </div>
JS
var $img = '<img src="https://skypeblogs.files.wordpress.com/2013/05/skype-button.png"/>';
$('.image').append($img);
JSFIDDLE DEMO
if you are using jquery, you can just do
var htmlString = '<div><figure><img src="some image src" /></figure></div>';
$('#ImageContainer').html(htmlString);
but if you are wanting to insert the div/figure and image separately, then you'd be best giving it some sort of identifier, i.e.
var htmlString = '<div><figure id="myFig"></figure></div>';
$('#ImageContainer').html(htmlString);
$('#myFig').html('<img src="" />');

Setting baseUrl for img tag in HTML fragment

I have a page hosted on domain1 from which I retrieve, with an ajax call, an HTML fragment which include some tags. These tags have a relative src URL and I want to set, for these tag only, a base URL pointing to another domain, say domain2.
Here's an example: I have a String HTMLData with the following value:
'<p> Foo </p> \
<img alt = "Image 1" src = "/relativepath/To/Image1"> \
<div class = "someDiv"> \
<img alt = "Image 2" src = "/relativepath/To/Image2"> \
</div>'
I want to add to my page something like:
'<p> Foo </p> \
<img alt = "Image 1" src = "http://domain2/relativepath/To/Image1"> \
<div class = "someDiv"> \
<img alt = "Image 2" src = "http://domain2/relativepath/To/Image2"> \
</div>'
Of course, I have no idea of the exact structure of the fragment, and I will probably want to extend it to other embedded object tags.
Here is what I have written so far:
function setBaseURLandConstructDiv (HTMLData) {
var container = document.createElement("div");
container.innerHTML = HTMLData;
var images = container.getElementsByTagName("img");
for (var image = 0;image<images.length;image++) {
if (images[image].src) {
images[image].src = 'http://domain2'+ images[image].getAttribute('src');
}
}
return container.innerHTML;
}
It works, but it doesn't seems right to me. In particular, at the line container.innerHTML = HTMLData, the browser make an unnecessary request to http://domain1/relativepath/To/Image1, before making the (correct) call to http://domain2/relativepath/To/Image1 at the line images[image].src = 'http://domain2'+ images[image].getAttribute('src');
So is there another method to modify the src attributes? (Or to locally set a base Url)
what happens when you use HTMLData to get the images for you array?
You could first change the HTMLData and then assign it to the container.

create new elements using javascript

In my Spring web application, for customer registration page I am adding and removing divs containing text, img and a-ref elements. When I write the code inside the same jsp the page works perfectly but according to my requirement when I try to put javascript code into a js file and import it and click add button a new div is inserted along with script code as given below,
the js function I am using to add a div is..
function addInputBox() {
var ni = document.getElementById('myDiv');
var numi = document.getElementById('theValue');
var num = (document.getElementById('theValue').value -1)+ 2;
numi.value = num;
var newdiv = document.createElement('div');
var divIdName = 'my'+num+'Div';
newdiv.setAttribute('id',divIdName);
var htmlString = '<div style="margin-top: 5px"><input type="text"name="service_name" title="Service Name" maxlength="200" style="width:400px;vertical-align:middle;"/>'+
'<img src="<c:url value="/resources/img/common/x.png" />" alt="" style="vertical-align:middle;margin-left: 5px"/>'+
'<img src="<c:url value="/resources/img/ope/new.png" />" style="vertical-align:middle;margin:2px 0 0 2px;margin-left: 5px" /> </div> ';
newdiv.innerHTML = htmlString;
ni.appendChild(newdiv);}
any idea what may went wrong? any help would be greatly appreciated..
pretty sure the script is there , because you are not escaping the quotation..try this
<img src="<c:url value=\"/resources/img/common/x.png\" />" alt="" style="vertical-align:middle;margin-left: 5px"/></a>'+
'<img src="<c:url value=\"/resources/img/ope/new.png\" />" style="vertical-align:middle;margin:2px 0 0 2px;margin-left: 5px" />
missing escape..."\" in ur img tag....
not sure wat c:url is...
hope this helps
I think its trying to render your <c:url part as a tags .... are you able to provide the paths to those images in the string explicitly?

Can't update iframe content with jquery

iframe is loaded dynamically into container div inside function.
With cc.text(content); I try to update #code content.
I check changed text in runtime, it's updated but on screen value remains the same.
I am not a javascript pro, so any comments are welcome:
function ShowEditor(content) {
var url = "XmlEditor/Editor.htm";
slHost.css('width', '0%');
jobPlanContainer.css('display', 'block');
frame = $('<iframe id="' + jobPlanIFrameID + '" src="' + url + '" class="frame" frameborder="0" />');
frame.appendTo(jobPlanIFrameContainer);
$(frame).load(function () {
var ifr = frame[0];
var doc = ifr.contentDocument || ifr.contentWindow.document;
var jdoc = $(doc);
var cc = jdoc.contents().find("#code");
// var tst = cc.text();
// alert(tst);
cc.text(content);
});
}
I get the text in commented code, but fail to update #code content.
iframe holds the following html where I omit details inside head and script:
<!doctype html>
<html>
<head></head>
<body>
<form>
<textarea id="code" name="code">some texts</textarea>
</form>
</body>
</html>
Your XML editor doesn't read more than once what's in the textarea.
A simple solution would be to generate in javascript the iframe content with the desired textarea content instead of loading it and then try to change the textarea content.
In fact (depending on the capacities of your XML Editor), you probably can do that directly in a generated text area instead of using a whole iframe to do it.

Categories

Resources