1

I have the following code inside a webpage:

<div id="search_suggest"></div>

Trying to use the following inside a javascript code changes the content inside the div brackets.

var ss = document.getElementById('search_suggest');
ss.innerHTML = 'asdasdasasddasasdasdasdasdasdasdasdasasdasd';

The following code, using Jquery as a selector, doesnt work (I checked, I'm selecting the right element):

  var ss =$(".search_suggest")
  ss.append( "<p>Test</p>"); #doesnt work
  ss.html("<p>Test</p>"); #doesnt work
  ss.text("<p>Test</p>"); #doesnt work

I also tried with plain text instead of html. Anyone have any ideas as why one works and the other doesn't? I don't believe I'm doing the tesxt or html wrong.

2
  • 1
    Use id selector # change $("#search_suggest") instead of $(".search_suggest") Commented Jan 7, 2016 at 13:01
  • 1
    Its because you are selecting by a class name while u have assigned an ID with that name to your element Commented Jan 7, 2016 at 13:01

3 Answers 3

4

search_suggest is ID of element. Use id selector # instead of class selector .:

$("#search_suggest")
Sign up to request clarification or add additional context in comments.

2 Comments

it worked! I've seen to have been using the # for class and . for id. Strangely enough, nothing has broke so far. Thanks
@virgula24: you were doing opposite of what needs to be done. use # for ID and . for class
2

In Jquery selectors # is used to getElementById is while . is used to getElementsByClassName.

use this var ss =$("#search_suggest") instead of var ss =$(".search_suggest")

Comments

2

Suggestion

If you must use a class or attribute selector, you can improve performance by specifying the optional context parameter.

ID is absolutely the **fastest**. Part of the reason is that ID is supposed to be unique, so the API stops searching after the ID is found in the DOM.

Better to use ::

$(".classname", "#idname")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.