I'm trying to write a Greasemonkey script. There is something like this in a webpage:
<div id="div1" class="..." title="
asdsadsadasd <e;...
">...</div>
I want to get its title using jQuery attr
method. But it returns an empty value. My js code is like this:
$("#div1").attr("title");
I've tried alert in many different ways and I'm sure that the required element is selected properly and all other attributes are fine! Just this one returns empty string! ( '' ) Does it have something to do with being multiline?
More details: I'm using latest jQuery (1.8.2) and my browser is Firefox 16.0.1. I saw this link and it worked there! So maybe it's because something else. Actually I'm coding in a Greasemonkey script which is altering a webpage that is not mine to edit. So editing the HTML code is not possible.
The title
is blank because it (or most likely the <div>
) is added via AJAX, after the Greasemonkey script fires.
Use the waitForKeyElements() utility to handle this kind of situation.
Here is a complete script that uses jQuery and waitForKeyElements
to grab that title:
// ==UserScript==
// @name _Grab element's title, when it is added by AJAX
// @include http://YOUR_SERVER.COM/YOUR_PATH/*
// @require http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js
// @require https://gist.github.com/raw/2625891/waitForKeyElements.js
// @grant GM_addStyle
// ==/UserScript==
/*- The @grant directive is needed to work around a design change introduced
in GM 1.0. It restores the sandbox.
*/
function grabDivTitle (jNode) {
//***** YOUR CODE HERE *****
var titleStr = jNode.attr ("title");
console.log ("Title is:", titleStr);
}
waitForKeyElements ("#div1", grabDivTitle);