i am trying to make an image named id='pr' a variable like this.
my HTML code is
<div id="main">
<img id ='pr' style="width: 500px;height: 600px;"src="https://i.redd.it/2u0y0z5i12py.png">
</div>
My javascript code:
<script type="text/javascript">
var getElementById('pr') = 1
if (getElementById('pr' = 1)) {alert ('im pickle rick bitch')}
</script>
So what i am trying to do is make a variable for pr and give it a value of one so it triggers the alert if pr is the image in the gallery.Hopefully i explained it good cause my english is not the best!(im also a noob)TY!
Your main issue is that if you make a variable for pr and then you set that variable to 1, you'll lose the reference to pr.
In other words:
var document.getElementById("pr") = 1;
is not valid code because you didn't specify a variable name. But, even if you did:
var x = document.getElementById("pr") = 1;
x would, at first hold a reference to pr and then immediately lose that value and instead be set to 1.
You also have a problem with your if condition because the single equal sign (=) is for setting a value, not comparing two values. So, your condition will always return true. JavaScript uses == and === for comparisons.
If you need a way to keep track of the element, you can give each element a data-* attribute as shown below:
var element = document.getElementById('pr');
// We can extract the data-count attribute value (a string)
// with the .dataset.count property:
if (element.dataset.count === "1") {
alert ('im pickle rick bitch');
}
<div id="main">
<!-- The data-* attributes are designed to allow you to store meaningfull data with an element. -->
<img id ='pr' data-count="1"
style="width: 500px;height: 600px;" src="https://i.redd.it/2u0y0z5i12py.png">
</div>
Try this:
var foo = document.getElementById('pr');
if (foo) {alert ('im pickle rick bitch')}
This will fix your issue with running the code and will only show if your id exists. But I suggest you have a look at some javascript tutorials. This will help you understand Suren Srapyan's answer better.
You can set a value for img, but as I understand you need to add some extra info on the img tag. You can do it via setAttribute and getAttribute methods.
In your code you have some errors. Your variable declaring is wrong. You need to give to your variable a name, in my case it's myPr and assign to it the vlaue which return document.getElementById not just getElementById. Then use setAttribute method to set some HTML5 constraint attribute called dataId. After it you can use getAttribute method to get that value and use in your logic.
const myPr = document.getElementById('pr');
myPr.setAttribute('dataId', 1);
if(Number.parseInt(myPr.getAttribute('dataId')) === 1) {
alert ('im pickle rick *****');
}
<div id="main">
<img id ='pr' style="width: 500px;height: 600px;"src="https://i.redd.it/2u0y0z5i12py.png">
</div>
Related
Sorry, I am just very new in this and had a previous experience in C++, and the question is it possible to do in javascript/html.
I want to make a function in JavaScript which replaces image on click using an array of image locations. Is it possible somehow to declare the needed variable (position number in the array) in the html? So I don't have to create a separate function for each individual image.
In the c++ you make a function and then declare a variable inside the brackets. Is it possible here, and if not, is there any close solution?
JavaScript:
var imgArray = ["images/2.jpg","images/3.jpg"]
function newImage() {
document.getElementById('pic').src = imgArray[1];
}
HTML:
<div class="project" id="ba">
<p onclick="newImage()">Poster</p>
</div>
Is it possible to insert the number in html "newImage(NUMBER)"?
You can send the index number from HTML and receive that in the javascript function as a parameter:
function newImage(index) {
document.getElementById('pic').src = imgArray[index];
}
// in the html
<div class="project" id="ba">
<p onclick="newImage(1)">Poster</p>
</div>
If you plan on using only one <p>, you can initialize a counter variable which gets incremented every time you click on "poster" label and mod it to the length of the images array. It would loop the available images.
var imgArray = ["images/2.jpg","images/3.jpg"]
var counter = 0;
function newImage() {
document.getElementById('pic').src = imgArray[counter];
counter = ++counter % imgArray.length;
}
<div class="project" id="ba">
<p onclick="newImage()">Poster</p>
</div>
<img id="pic" src="#"/>
Else, update your newImage() function to have an argument newImage(index) and pass the needed index in your <p onclick="newImage(1)">poster</p>
You can't really declare variables in HTML. So it's impossible to do something like onclick="newImage(variable);", with exclusively HTML. If you're using a framework like ASP.NET you can do things like onclick="newImage(#variable);" using Razor. I believe Angular, React, etc. all provide similar functionality.
However, there are other ways to achieve something similar in a "vanilla" setup.
If it's just a static number you can pass it with no variable. Something like onclick="newImage(3);"
You can also set a value attribute which can be accessed in JavaScript as well. something like <p id="poster" value="3" onclick="newImage();">Poster</p>.
Then in JS:
function newImage(){
value = document.getElementById("poster").value;
/* do something with the value */
}
If you're using PHP you can also pass PHP variables to JavaScript through the onclick function as demonstrated here. I would recommend this route if you're dynamically generating your HTML (e.g. within a PHP loop) and might not want to hard code each individual value.
I am using following code:
...
<div id="divcontainer1">
...
<div id="divcontainer2">
...
</div>
</div>
...
Now, I want change "divcontainer2" at a later point of time in the Div "divcontainer3".
What is the right way to check is exist divcontainer2 and when true,
change in divcontainer2 width javascript ?
Thank you,
Hardy
It is probably not nest practice but you can do this by changing the .outterHTML of the element. You would likely want to improve on this but here is a quick example. The last line checks if div 2 exists.
var div2 = document.getElementById("div2");
var html = div2.outerHTML;
var idx = html.indexOf(">");
var newtag = html.substring(0, idx).replace("div2", "div3");
div2.outerHTML = newtag + html.substring(idx, html.length - 1);
var contents = document.getElementById("div3").innerHTML;
alert(document.getElementById("div2") != undefined);
All you do is
get the element .outterHTML
get the substring representing the tag.
Replace the text that defines it
Set the .outterHTML tag to our new string
Now you have a newly named div that keeps all of its attributes, position in the parent and content.
The alert line is how you check for the existence of an object.
I don't believe that there is a "proper" way to do this, however I would store the contents of divcontainer2 in a variable, and then do something like this
var containerOfDivContainer2 = document.getElementById("containerofdiv2");
containerOfDivContaier2.innerHTML = "<div id='divcontainer3'>"/* insert div contents */+"</div>";
Of course, this requires you to put divcontainer2 in a div called containerofdiv2 but it works.
If using jQuery, this will do it:
$('#divcontainer2').attr('id','divcontainer3');
But you shouldn't be changing IDs. Use classes instead and then use the jQuery's toggleClass() function, like:
<div id="divcontainer1">
...
<div id="divcontainer2" class="style1">
...
</div>
$('#divcontainer2').toggleClass("style1 style2");
I've been searching and trying different codes, but I don't came up to a solution.
This script i'm trying to create do this:
When the user clicks inside a div with class="Box". The program will save in a variable the content of the Box.
var boxContent = $(this).parents('.Box')[0].innerHTML;
So, the value of the variable boxContent now (acording to my html output will be) returns the hole div that the user clicked:
<div class="Box">
<div class="URL_ID">
<span>http://test.com</span>
<span id="ID">3232434</span>
</div>
<div class="info">
</div>
<div class="secondLink">
</div>
</div>
Now what i'd like to take is the div to process later and do an append in a table. So i tried to use find(), but doesn't work...
var url = boxContent.find('.BoxSongUrl');
What can i do??
Thanks in advance.
Your statement:
So, the value of the variable boxContent now (acording to my html output will be) returns the hole div that the user clicked:
Is not true. innerHTML returns a string of the markup html inside the element. To use the Jquery's .find() method, you have to actually select the Jquery object:
var url = $(this).parents('.Box').find('.BoxSongUrl');
You can use clone to retain a copy of the first '.Box' element at the time the query is run.
var boxContent = $(this).parents('.Box').first().clone();
Then, you can use the find method on boxContent
var url = boxContent.find('.BoxSongUrl');
EDIT:
If you would rather not clone the whole jQuery object you would save the html and re-parse it before calling find.
var boxContent = $(this).parents('.Box').first().html();
Then, re-parse the HTML into a jQuery object:
var url = $(boxContent).find('.BoxSongUrl');
I just asked a question here about selecting all id's of the form id_* where * is any string and id is the id of the element. I got a great working solution:
$("*[id^=" + id + "_]").each(function() {... // id is the element name
I need to take this one step further now:
All of my ids will be of the form: a_b_c ... where a b and c are arbitrarity strings (that do NOT contain a ''). So, now rather than selecting all the elems of the form id_* where * could be a_b_c ... I need only to select 1 level deep: i.e. all elems of the form id_a. So in other words it stops at the next ''. Is this possible?
As an example:
If my id is: first
And there exist id's: first_second, first_second_third
It will select only first_second
Sounds like you are storing too many values in the id of the field. With HTML5 we now have data- attributes.
Perhaps, you should be making use of data- attributes something like this to link them?
<div id="a">
</div>
<div id="b0" data-parentId='a'>
</div>
<div id="b1" data-parentId='a'>
</div>
<div id="b2" data-parentId='a'>
</div>
<div id="c" data-parentId='b1'>
</div>
It will still validate, as any non-standard attribute starting with data- will be considered valid.
See: http://ejohn.org/blog/html-5-data-attributes/
Your jQuery selectors can then make use of this new attribute, rather than trying to parse strings
Something like this would select all of a's children
var childrenOfA = $("div[data-parentId='a']);
What I ended up doing (and I'm open to faster implementations) is:
$("*[id^=" + id + "_]").each(function() {
//here I simply split the id and test the size of the array
//if its too large (i.e. too deep in the tree), I return true (to continue
// to the next iteration):
var row = $(this);
var split = row.attr('id').split("_");
if(split.length > SOME_PREDETERMINED_VAL)
return true;
//code here
});
I am not totally happy with this since it still traverses all elements (or would it do this anyway regardless of the filter in the each() function??).
This doesn't give you the whole solution, but you could try the attribute prefix selector or the attribute starts with selector
That will allow you to select any descendant of an element:
$("[id^='a_b_']").each(....
Will think how to remove the grandchildren etc, but this might get you started.
EDIT
I have just found that a similar question was asked about jQuery wildcards - this looks as if it will do what you need.
It seems like you are seriously overcomplicating this task. Let's say your structure is currently like this:
<div id="a">
<div id="a_b">
<div id="a_b_c">
</div>
</div>
</div>
Why don't you just do something along these lines...
<div id="a">
<div class="b">
<div class="c">
</div>
</div>
</div>
So, if I JUST wanted #a .b I would do:
$("#a .b").not("#a .c").show();
Makes it a bit more semantic and readable as well. Am I understanding what you're trying to do? Might need to shed a bit more light on what exactly you're doing
The obvious solution is changing your document, for example instead of
<div id="a"></div>
<div id="a_b"></div>
<div id="a_b_c"></div>
you could write
<div id="a" class="l1"></div>
<div id="a_b" class="l2"></div>
<div id="a_b_c" class="l3"></div>
and then select $('.l2[id^=a_]'). If that is not an option, you could try some sort of sieve scheme:
var set = $('[id^='+id+'_]'), i = 0;
while (i < set.length) {
var e = set.eq(i);
if (e.attr('id').substr(id.length+1).match('_')) {
set = set.not(e);
} else {
i++;
}
set = set.not($('[id^='+e.attr('id')+'_]'));
}
(I haven't tested, so there might be errors, and I'm not sure not is the one that subtracts from a result set, but you get the idea.)
It depends on the document structure and browser whether this will be actually faster than the naive implmentation of simply walking through the while set and skipping everything with two _ in the id. (High number of branches per node helps, and it will be probably faster on browsers which have a native implementation of the CSS3 prefix selector which jQuery can call on.)
update: fixed some mistakes. The logic might change depending on your structure, e.g. the innermost if branch is unnecessery if foo_bar always precedes foo_bar_baz.
What I need to do is be able to store some piece of data about an element.
For example, lets say I have a list item <li>, and I want to store some data about it in the element, like "This is element 1 from XYZ".
The only way I know how to do this (which I don't want to do if I can avoid) is this:
<li id='item1'>
Item 1
<!--This is element 1 from XYZ-->
</li>
<script>
// read it something like this
var e = document.getElementById('item1').innerHTML;
// then parse out the comment, etc.
// --
</script>
What I really want is something like this (which I am fairly certain is not possible):
// example
<li id='item1' userdata='This is element 1 from XYZ'>Item 1</li>
.. of course, I would like to be able to access it somehow via javasscript.
Alternatively, is there some other way to achieve this?
Thanks -
You can access your userdata="" attribute from JavaScript. Just do:
var theData = document.getElementById('item1').getAttribute('userdata');
If you want to do it the HTML5 way, then you would use attributes named data-*, e.g.:
<li id='item1' data-foo='This is element 1 from XYZ'>Item 1</li>
that way it will still be valid (i.e., it'll make you feel better for not using an invalid attribute). New browsers will support accessing the data-* attributes like so:
var theData = document.getElementById('item1').data.foo;
but I don't think that is implemented widely enough to rely upon yet.
If you do want to store the data in a comment (although I'd advise going the attribute route instead) you could do something like:
var e = document.getElementById('item1');
var n = e.firstChild;
while (n && n.nodeType != Node.COMMENT_NODE) {
n = n.nextSibling;
}
// now n.nodeValue will have the comment contents
(No guarantees about whether IE likes any of the above.)
You can't add arbitrary elements to HTML. Well you can but it won't be valid and beheaviour is undefined. For this kind of thing I tend to use jQuery. It has a data() call that can add arbitrary data to an element. I believe it encodes it in the class attribute but the implementation is not important.
You could do this yourself but why bother? It's easy to get wrong by putting the wrong characters in, not correctly escaping/unescaping data or inadvertently destroying informatino. Instead just do:
$("#item1").data({source: "Thsi is element 1 from XYZ"});
Since you can accept adding comments, a better solution would be to add a span element with the content you wanted..
<span class="data">.....</span>
you define your data class to have display:none and it is invisible ...
this way you can have access to it with the normal DOM traversing methods..
You can use setUserData() and getUserData() function
http://www.w3.org/TR/2004/REC-DOM-Level-3-Core-20040407/core.html#Node3-setUserData
For example:
<html>
<head>
<script type="text/javascript">
function set(){
var a = document.getElementById("testElement");
a.setUserData("testData", "Some text", null);
}
function get(){
var a = document.getElementById("testElement");
alert(a.getUserData("testData"));
}
</script>
</head>
<body>
<span id="testElement"/>
<form>
<input type="button" value="setUserData" onclick="set()"/>
<input type="button" value="getUserData" onclick="get()"/>
</form>
</body>
If you don't need the HTML to be valid, you can make any attribute you want, and you can access it in Javascript by calling the getAttribute method.
You can add a nested invisible element with an id and your data as the innerText. Use the style attribute to make sure it's invisible.
But it all really depends on what you're trying to achieve. Could you elaborate more?
// If you want to include data in the html why not give it its own node?
.hiddendata{
display: none
}
<li id= 'item1'>
Item 1
<span class= "hiddendata"> This is element 1 from XYZ</span>
</li>
function readHiddenData(who){
var A= [], n= who.firstChild;
while(n){
if(n.className= 'hiddendata'){
A[A.length]= n.textContent || n.innerText || '';
}
n= n.nextSibling;
}
return A;
}
function showHiddenData(who){
var n= who.firstChild;
while(n){
if(n.className= 'hiddendata'){
n.style.display= "inline"
}
n= n.nextSibling;
}
}