I (am pretty sure I) have to use jQuery for a portion of a page I'm trying to create and this is basically my first day doing jQuery.
For the following if/else, I'm first trying to check if a <div>
with an id equaling the variable url
exists. If it exists, it will write text into the div. If the element does not exist, the else
will create a new div with an id
attribute, and text containing the same response, and append it to an <a href>
tag associated with it.
Function() {
...
...
...
if (xhr.readyState == 4 && xhr.status == 200) {
if ($("div#"+url+"").length) {
document.getElementById(url).innerHTML = xhr.responseText;
}
else {
$("a[href='" + link + "']").append(
$("<div></div>", {
"id": url,
"text": xhr.responseText
}
)
);
}
}
...
...
}
If I made that sound confusing, here's a visual representation of what I want to have happen in the HTML DOM.
Before
<a href="http://foo.com" onclick="Function('url')">Foo</a>
After link is clicked.
<a href="http://foo.com" onclick="Function('url')">Foo</a><div id="http://foo.com">xhr.responseText</div>
The error I get in the console is
Error: Syntax error, unrecognized expression: div#http%3A%2F%2Fwww.foo.com
Because it says it is a syntax error, I know I must be using .length wrong, but the selector for id
is #
so I don't understand where the error is. I've done a bunch of scouting across SO and http://api.jquery.com/length/ for jquery syntax for checking if a child exists and I've tried using some logical operators but it's always the same error at the if statement. I also tried using encodeURIComponent(url) in case it didn't like some characters in the URL but that didn't fix it either.