If I have a some javascript in an anchor's href attribute:
<a href="javascript:alert('hello!')">
Is there a way I can get a reference to the DOM element that was clicked when the script executes? I mean, I know I could do
<a href="javascript:alert('hello from '+document.getElementById('thisAnchor'))" id="thisAnchor">
But I was hoping for something more like
<a href="javascript:alert('hello from '+target)">
Something like this?
Example: http://jsfiddle.net/TTzDb/
me
Using onclick, this will refer to the element that received the event.
Move the JavaScript to the onclick="yourJavaScriptHere" attribute. Then you can use the 'this' keyword to reference your anchor. So
some text
Although, that isn't very meaning. Additionally, it is a better practice to separate your JavaScript from your HTML to build a more maintainable website.
Yes, and the answer is this which refers to current DOM element:
Click me
EDIT:
Of course as bobince mentioned (see comments) that won't work as excepted. The correct form is:
Click me
Related
How to use click event on tag without id
Hello everybody, I have a html tag bellow:
<a class="fc-day-grid-event fc-h-event fc-event fc-start fc-end fc-draggable fc-resizable" href="https://www.youtube.com/watch?v=XXXXX"><div class="fc-content"> <span class="fc-title">event</span></div><div class="fc-resizer fc-end-resizer"></div></a>
this html code was built automatically by jquery so I can't add id or "onlick" event on this tag.
What I want is when I click on this tag, it will open a new windows with href for me. I tried to use
$('.fc-day-grid-event).on('click, function() {
...//
});
But it's not working.
How should I do for this case? Please help.
this html code was built automatically by jquery so I can't add id or "onlick" event on this tag
If you can't control when that happens, you can still use event delegation to get involved in the click event:
$(document).on('click', '.fc-day-grid-event', function() {
...//
});
That works even if the code runs before the element exists. The code in your question only works if the element exists as of when your code runs. See the documentation for details.
As the code is generated after the page rendering, you should use a delegated event handler:
$('body').on('click','.fc-day-grid-event', function() {
//...
});
The original code is missing apostrophes after the class name and after the 'click'.
This should work:
> $('.fc-day-grid-event').on('click', function() {
...//
});
However you might consider to check, if there are other dom elements with that class. An ID is much safer. A workaround could be to use multiple classes in the jQuery selection by selecting the element(s), that matches them all:
$('.fc-day-grid-event.fc-h-event.fc-event.fc-start.fc-end.fc-draggable.fc-resizable')
but this might still be not sufficient, because these framework-classes seem to be dynamically created and maybe deleted and the selection might be too wide or too narow. You could try to select the a tag with parent/child relations, where you know, that you are getting the right element and you could even use the innerHTML of the elements. Alternatively you could iterate through a JQuery-Selection and check for certain attributes.
I'm not sure, if you want to change the target of the link or the target window of the link. Opening the target of a link in a new window works with standard html by using the target attribute
<a href='bla' target='_blank'>bla ...
If you use Javascript for manipulating the target adress of a link outside of the href, the code might get hard to maintain in most contexts and the user might get confused, because he get's to page, he didn't expect. I would try to manipulate the Javascript, that is creating the a tag or if that's really impossible, i would manipulate the existing a tag according to my needs and change the attributes like this, if you want to use jQuery:
For the target address of the link:
$('.fc-day-grid-event').attr("href", "www.newhrefvalue.com")
Or for opening the link in a new tab:
$('.fc-day-grid-event').attr("target", "_blank")
Then you don't need to prevent or emit events or create event listeners.
<a onclick="doStuff(this)">Click Me</a>
Using and html element's addEventListener has several advantages over using inline events, like onclick.
However, to store the element including its inline event is straight forward, for example, by embedding it in a parent element and storing the parent's innerHTML.
Is it possible to do something similar when using event listeners?
Edit:
I realized that my question is not sufficiently explained. So here some additions.
By "store" I mean a way to get the information holding the element and the event listener.
The analogue with inline events is easy: just embed in a parent element and save the parent's innerHTML (string) somewhere, for example in a database, and recreate the element later by loading the string and applying it to the innerHTML of some element.
But how would one do the analogue with elements when using event listeners? One cannot just use the innerHTML since then the events are not stored.
I hope this clarifies my question a bit.
Edit 2
With the help of comments I have made some unsuccessful attempts.
It is possible to get store the information of an element using createDocumentFragment() or element.cloneNode(true).
However, the first method does not work for external storage since, if I understood correctly, will contain only a pointer. Here is an example:
https://jsfiddle.net/hcpfv5Lu/
The second method does not work either. I am not fully sure why, but if I JSON.stringify the clone it "vanishes". Here is an example:
https://jsfiddle.net/3af001tq/
You could use a document fragment to store the DOM node in a JavaScript variable which can then be appended to a DOM element when required.
https://developer.mozilla.org/en/docs/Web/API/Document/createDocumentFragment
Yes.
You can use something like.
<ul>
<li id="list">Some data</li>
<li>Dumy</li>
</ul>
then in your javascript file,
document.getElementById("list").addEventListener("click", function(){
var htmlMarkUp = this.parentNode.innerHTML;
});
This would store the html content of ul in var htmlMarkUp.
Why doesn't this work in a browser?
<input type="button" id="x">
Click
Yes, I know that I can use onClick to call a function and put my code there, but is there a way to use 'javascript:' with the href attribute to do simple javascript functions like changing a value?
Assignment "returns" the value assigned. Returning any kind of value from a javascript: link indicates to the browser that it should replace the document with that value.
Usually you might see javascript:void(stuff goes here) to suppress the return value.
You already seem to be aware of why you shouldn't do this, though. onClick event handler is a step in the right direction, but really it should be attached externally.
Yes, that should work and as you know onclick is another easy approach to do it;
However if you still want to it with href you may try this -
(this might look unwillingly big :)
<input type="button" id="x">
Click
I need to pass the contents of an inside div to a function, for example myfun(string). I have tried using
myfun((this).children[0].innerHTML)
myfun((this).children[1].innerHTML)
myfun((this).children[0].children[0].innerHTML)
but none of those seem to work. I can't just pass the getElementById value because the function should be generic since it would be called by php on various <a> elements (ideally I think it should include the this. keyword).
Thanks for any help.
If you don't need it to work cross-browser, there's:
this.getElementsByClassName('label')[0]
This will fail in IE 8 and below.
If you're absolutely certain the HTML/DOM structure won't change, you could perhaps use:
this.nextSibling.children[0];
But this might have issues in browsers that consider textNodes as childNodes
in your function, "this" refers to the link, and can't be used.
a much cleaner solution would be to have myfunc know that it is going to receive an object which contains the text
javascript:
myfunc(obj){
alert(obj.childNodes[0].nodeValue);
}
html
click
<div id="target">target contents</div>
The object this will apply to the <a> tag that it calls. You need to call the parent div first and then select the children accordingly.
Try using this.parent.children[1].children[0].innerHTML
Try
this.parent.children[1].children[0].innerHTML
But you should really use dynamic IDs instead of this mess.
i have an element in html as shown below.
<tr><td class="HELPTEXT"><span lang="HLPMTXT1" id="HLPMTXT1"></span></td></tr>
i want to change the value of lang according to particular condition.
I tried as given below.but its not working.
<script>
document.getElementById("HLPMTXT1").lang ="HLPMTXT2"
</script>
Could anyone help me for changing the value of lang attribute of span?
You should use setAttribute(name, value) to do that, so your code would look like:
document.getElementById("HLPMTXT1").setAttribute("lang", "HLPMTXT2");
You can also use getAttribute(name) to retrieve the value using JavaScript.
https://developer.mozilla.org/en/DOM/element.setAttribute
https://developer.mozilla.org/en/DOM/element.getAttribute
Edit: It's also possible that your script is not working because you're trying to access the element before it exists in the DOM. Best way to insure that your element exists is by either: a) putting your script tag after the element, b) using the unload event to delay execution of your JS until everything is loaded, or c) use the DOMContentLoaded event. The latter, however, is a bit tricky to get to work cross-browser (without reusing somebody else's code that already addresses those problems) so you might want to read up on it first.
document.getElementById('HLPMTXT1').setAttribute('lang', 'HLPMTXT2');
Not all attributes can be accessed through the object properties