BYC
BYC

Reputation: 33

Adding element to document OR element depending on not null

Having a hard time adding an element into another element. my approach is unique. basically the user either enters a selector or by default it is the document.

so we have 2 buttons, one which specifies a selector and one which does not.

<button onClick="callFunction({where:'#test'})"> Test selector</button>
<button onClick="callFunction()"> default</button>

and the function "callFunction":

function callFunction(arguments){
    scope= (arguments.where===undefined? $(document) : $(arguments.where));
    createElementIn(scope);
}

then calls the createElementIn(scope) function and creates the element in the selector given

function createElementIn(scope){
var newdiv = document.createElement('div');
       $(newdiv).css("position", "absolute");
       $(newdiv).css("left", "500px");
       $(newdiv).css("bottom", "500px");
       $(newdiv).css("display", "block");
       newdiv.innerHTML = str;
       scope.append(newdiv);//Over here, it does not append

}

I have a feeling im mixing up when to do $(scope)... and when to leave it scope... document.body.appendChild works but i cant pass document.body into the scope. please, whats the right approach to solving this?

Upvotes: 0

Views: 52

Answers (3)

Arun P Johny
Arun P Johny

Reputation: 388346

The default scope should be body element - not document, also the elements was not visible because of the absolute positioning of the elements.

You were using a mix of native and jQuery, I've updated it to a jQuery solution - you can add additional styles to the .css({...}) method

function callFunction(params){
    var scope= ($.isPlainObject(params) && params.where) ? $(params.where) : $('body');
    createElementIn(scope);
}
function createElementIn(scope){
    var newdiv = $('<div />', {
        html: 'some content'
    }).css({
        //position: 'absolute',
        display: 'block',
    })
    scope.append(newdiv);
}

Demo: Fiddle

Upvotes: 1

Warlock
Warlock

Reputation: 7471

You are mixing jQuery with a native javascript. Use only jQuery to avoid misunderstanding.

I faced with a practice of using $ prefix before jquery selectors, for example you could write:

var $scope = (arguments.where===undefined? $(document) : $(arguments.where));
...
$scope.append(newdiv)

In this case you will know, that you don't need to wrap $scope with jQuery like this $($scope)

Upvotes: 0

jcubic
jcubic

Reputation: 66570

Try:

function createElementIn(scope){
    $('<div/>').css({
        position: "absolute",
        left: "500px",
        bottom: "500px",
        display: "block"
    }).appendTo(scope);
}

Upvotes: 0

Related Questions